<template>
  <div class="account-management">
    <div class="top-area">
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">添加用户</el-button>
      <el-input
          v-model="searchKeyword"
          placeholder="请输入检索内容"
          clearable
          class="search-input"
          @clear="handleSearch"
          @keyup.enter.native="handleSearch"
      >
        <el-select v-model="searchType" slot="prepend" style="width: 120px;">
          <el-option label="所有权限" value="all"/>
          <el-option label="管理员" value="管理员"/>
          <el-option label="可编辑" value="可编辑"/>
          <el-option label="可查看" value="可查看"/>
        </el-select>
        <el-button slot="append" icon="el-icon-search" @click="handleSearch"/>
      </el-input>
    </div>

    <el-table :data="tableData" border style="width: 100%; margin-top: 20px;">
      <el-table-column prop="username" label="账号"/>
      <el-table-column prop="name" label="姓名"/>
      <el-table-column prop="role" label="权限"/>
      <el-table-column prop="updateTime" label="最后更新时间">
        <template slot-scope="scope">
          {{ scope.row.updateTime ? new Date(scope.row.updateTime).toLocaleString() : '' }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="80">
        <template slot-scope="scope">
          <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="val => handleStatusChange(val, scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[15, 30, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="pagination"
    />

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" @close="resetForm">
      <el-form :model="formData" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="账号" prop="username">
          <el-input v-model="formData.username" :disabled="isEdit"/>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name"/>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input v-model="formData.password" type="password" show-password/>
        </el-form-item>
        <el-form-item label="权限" prop="role">
          <el-select v-model="formData.role" style="width: 100%">
            <el-option label="管理员" value="管理员"/>
            <el-option label="可编辑" value="可编辑"/>
            <el-option label="可查看" value="可查看"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from '@/utils/request';

export default {
  name: 'AccountManagement',
  data() {
    return {
      searchKeyword: '',
      searchType: 'all',
      tableData: [],
      currentPage: 1,
      pageSize: 15,
      total: 0,
      dialogVisible: false,
      dialogTitle: '添加用户',
      isEdit: false,
      submitLoading: false,
      formData: {
        id: null,
        username: '',
        name: '',
        password: '',
        role: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户账号', trigger: 'blur' },
          { min: 3, max: 10, message: '长度为3-10个字符', trigger: 'blur' }
        ],
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '密码长度为6-16个字符', trigger: 'blur' }
        ],
        role: [{ required: true, message: '请选择权限', trigger: 'change' }]
      }
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    async fetchData() {
      try {
        const res = await axios.get('/admin/employee/page', {
          params: {
            page: this.currentPage,
            pageSize: this.pageSize,
            name: this.searchKeyword,
            role: this.searchType === 'all' ? '' : this.searchType
          }
        });
        if (res.code === 1) {
          const {records = [], total = 0} = res.data || {};
          this.tableData = records.map(item => ({
            id: item.id,
            username: item.username || '',
            name: item.name || '',
            role: item.role || '',
            updateTime: item.updateTime || '',
            status: item.status === 1 ? 1 : 0
          }));
          this.total = total;
        } else {
          this.$message.error(res.msg || '获取数据失败');
        }
      } catch (error) {
        console.error('获取数据失败:', error);
        this.$message.error('获取数据失败');
      }
    },

    async handleSubmit() {
      this.$refs.form.validate(async valid => {
        if (!valid) return;

        this.submitLoading = true;
        try {
          const url = this.isEdit ? '/admin/employee/edit' : '/admin/employee';
          const method = this.isEdit ? axios.put : axios.post;
          const res = await method(url, this.formData);

          if (res.code === 1) {
            this.$message.success(this.isEdit ? '修改成功' : '添加用户成功');
            this.dialogVisible = false;
            this.fetchData();
          } else {
            this.$message.error(res.msg || (this.isEdit ? '修改失败' : '添加用户失败'));
          }
        } catch (error) {
          console.error('操作失败:', error);
          this.$message.error(this.isEdit ? '修改失败' : '添加用户失败');
        } finally {
          this.submitLoading = false;
          
        }
      });
    },

    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该用户吗？', '提示', {type: 'warning'});
        const res = await axios.delete(`/admin/employee/${row.id}`);
        if (res.code === 1) {
          this.$message.success('删除成功');
          this.fetchData();
        } else {
          this.$message.error(res.msg || '删除失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error);
          this.$message.error('删除失败');
        }
      }
    },

    async handleStatusChange(status, row) {
      try {
        const res = await axios.put(`/admin/employee/status/${status}`, {id: row.id});
        if (res.code === 1) {
          this.$message.success('状态修改成功');
          this.fetchData();
        } else {
          this.$message.error(res.msg || '状态修改失败');
        }
      } catch (error) {
        console.error('修改状态失败:', error);
        this.$message.error('修改状态失败');
      }
    },
        handleEdit(row) {
      this.isEdit = true;
      this.dialogTitle = '编辑用户';
      this.formData = {...row, id: row.id}; // 确保 id 被复制
      this.dialogVisible = true;
    },


    handleSearch() {
      this.currentPage = 1;
      this.fetchData();
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchData();
    },

    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchData();
    },

    handleAdd() {
      this.isEdit = false;
      this.dialogTitle = '添加用户';
      this.dialogVisible = true;
      this.$nextTick(() => this.$refs.form.resetFields());
    },

    resetForm() {
      this.$refs.form.resetFields();
      this.formData = {id: null, username: '', name: '', password: '', role: ''};
    }
  }
};
</script>

<style scoped>
.account-management {
  padding: 20px;
}

.top-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>